package com.honeymoondesert.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sun.swing.internal.plaf.metal.resources.metal;


public class MapUtil {
	String ak;
	String callback;
	String output;
	
	Logger log=Logger.getLogger(this.getClass());
    public MapUtil() {
    	Properties prop =  new  Properties();    
        InputStream ins = getClass().getResourceAsStream( "/config.properties" ); 
        try {
			prop.load(ins);
			ak = prop.getProperty( "ak" ).trim(); 
	        callback = prop.getProperty( "callback" ).trim(); 
	        output = prop.getProperty( "outputType" ).trim(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    
        
	}
	/**
	 * 
	 * @param address1      地址1
	 * @param address2  地址2
	 * @param c1        地址1所在城市
	 * @param c2    地址2所在城市
	 * @return    double类型，单位米
	 * @throws IOException
	 */
	public Double getDistance(String address1,String address2,String c1,String c2) throws IOException   {

		address1 = trimAll(address1);
		address2 = trimAll(address2);
		address1 = MapUtil.removeSign(address1);
		address2 = MapUtil.removeSign(address2);
		c1 = trimAll(c1);
		c2 = trimAll(c2);
		c1 = MapUtil.removeSign(c1);
		c2 = MapUtil.removeSign(c2);
		JsonObject j1 = lngAndLat (address1,c1);
		JsonObject j2 = lngAndLat (address2,c2);
		Double d = getDistanceByJs(j1, j2);
//		System.out.println(d);
		return d;
	}
	
	public String trimAll(String str){
//		int lastIndex = str.lastIndexOf("(");
//		if (lastIndex != -1) {
//			str = str.substring(0,lastIndex);
//		}
		
		String[] strs = str.split(" ");
		String str2 = "";
		for (String string : strs) {
			if (!string.equals("")) {
				str2 += string;
			}
		}
		return str2;
	}
	
	//地球半径
	private final  double EARTH_RADIUS = 6378.137;
	  //计算弧长
	private static double rad(double d){
	   return d * Math.PI / 180.0;
	}
	
	/**
	 * 根据经纬度 ，计算两地点的距离
	 * @param j1   {"lng":116.39564503788,"lat":39.92998577808};
	 * @param j2
	 */
	public  Double getDistanceByJs(JsonObject j1,JsonObject j2){
		if (j1!=null && j2 != null) {
			double lng1 = Double.valueOf(j1.get("lng").getAsString());
			double lat1 = Double.valueOf(j1.get("lat").getAsString());
			double lng2 = Double.valueOf(j2.get("lng").getAsString());
			double lat2 = Double.valueOf(j2.get("lat").getAsString());
			double radLat1 = rad(lat1);
			double radLat2 = rad(lat2);
			double a = radLat1 - radLat2;
			double b = rad(lng1) - rad(lng2);
			double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
					Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
			s = s * EARTH_RADIUS;
//	   s = s * 1000;
			s = Math.round(s * 10000) / 10;
			return s;
//	   System.out.println(s+"米");
			
		}else{
			log.error("地址不能识别，计算距离失败。");
			return null;
		}
	}
	

	
	/**
	 *     获取经纬度
	      Geocoding API Web服务API 
	 * 
	 * @param address		地址
	 * @param sh           地点所在城市
	 * @param output         返回的格式
	 * @return jsonObject  格式{"lng":116.39564503788,"lat":39.92998577808}
	 * @throws IOException 
	 * @throws Exception 
	 * @throws IOException 
	 * @throws IOException
	 */
	public JsonObject lngAndLat(String address,String sh) {
		try {
			address = URLEncoder.encode(address, "utf-8");
			sh = URLEncoder.encode(sh, "utf-8");
			URL resjson = new URL("http://api.map.baidu.com/geocoder/v2/?ak="
					+ ak + "&callback=" + callback + "&output=" + output + "&"
					+ "address=" + address + "&city=" + sh);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					resjson.openStream()));
			String res;
			StringBuilder sb = new StringBuilder("");
			while ((res = in.readLine()) != null) {
				sb.append(res.trim());
			}
			in.close();
			String str = sb.toString();
			str = str.substring(str.lastIndexOf("{"), str.indexOf("}") + 1);//可能地址不识别，返回格式不一样。出现异常返回null
			if (str.indexOf("lng") != -1) {
				JsonObject jsonObject = new Gson().fromJson(str,
						JsonObject.class);
				return jsonObject;
			} else {
				//System.out.println("地址"+address+"不能识别,得到经纬度失败!");
				log.error("地址" + URLDecoder.decode(address, "utf-8")+ "不能识别,得到经纬度失败!");
				return null;
			}
			//		System.out.println(URLDecoder.decode(address,"utf-8") +"=============="+str);
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}
	public Double getDistancebyAddress(String start,String end) {
		MapUtil du=new MapUtil();
		Double distance =null;
		try {
			JsonObject s = du.lngAndLat(start, "sh");
			JsonObject e = du.lngAndLat(end, "sh");
			distance = du.getDistanceByJs(s, e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return distance;
	}
	public static String removeSign(String str){
		String result="";
		boolean isCont=true;
		for (int i=0;i<str.length();i++) {
			if(str.charAt(i)=='('||str.charAt(i)=='（'){
				isCont=false;
			}
			if(isCont)result+=str.charAt(i);
			if(str.charAt(i)==')'||str.charAt(i)=='）'){
				isCont=true;
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		MapUtil mu=new MapUtil();
		try {
			System.out.println(mu.lngAndLat("南桥镇百齐路288号百联南桥购物中心2期1楼中庭G4(近南奉公路)","上海"));
			System.out.println(mu.lngAndLat("南桥镇百齐路588号东方商厦1楼(近南奉公路)","上海"));
			System.out.println(mu.getDistance("南桥镇百齐路288号百联南桥购物中心2期1楼中庭G4(近南奉公路)", "南桥镇通阳路398号", "上海", "上海"));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(MapUtil.removeSign("南桥镇百齐路288号百联南桥购物中心2期1楼中庭G4(近南奉公路)"));
	}

	
	
}
